package com.yicong.ants.ui.video;

import android.graphics.Color;
import android.util.Pair;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.fragment.BaseStatefulFragment;
import com.cchao.simplelib.util.StringHelper;
import com.x.livesdk.util.http.DataCallBack;
import com.x.livesdk.util.http.HttpUtil;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.global.ClientConfig;
import com.yicong.ants.databinding.VideoMainFragmentBinding;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.ad.AdManager;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.ui.video.live.LiveFragment;
import com.yicong.ants.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author glj
 * @version 2021/2/25 0025
 */
public class VideoMainFragment extends BaseStatefulFragment<VideoMainFragmentBinding> implements View.OnClickListener {
    List<Pair<String, Fragment>> mFragments = new ArrayList<>();
    FragmentStatePagerAdapter mAdapter;
    public static int mCurPage;

    @Override
    protected int getLayoutId() {
        return R.layout.video_main_fragment;
    }

    @Override
    protected void initEventAndData() {
        mDataBind.setClick(this);
        StatusBarUtil.setStatusImmerAndTextWhite(getActivity().getWindow());
        mDataBind.topField.setPadding(UiHelper.dp2px(15), StatusBarUtil.getStatusBarHeight(mContext), UiHelper.dp2px(15), UiHelper.dp2px(15));
//        initAdapter();
        initPage();
        onLoadData();
    }

    private void initPage() {
        initFragments();
        initViewpager(false);
    }

    private void initFragments() {
        mFragments.clear();
        mFragments.add(Pair.create("关注", new VideoListFragment().setPageIndex(0)));
        mFragments.add(Pair.create("推荐", new VideoListFragment().setPageIndex(1)));

        Fragment ksFragment = getKsFragment();
        if (ksFragment != null) {
            mFragments.add(Pair.create("热门", ksFragment));
        }
    }

    private void loadLive() {
        ClientConfig.WebUrl url = ZzConfigs.getClientConf().getWeb_url().get("live_api");
        if (url != null && StringHelper.isNotEmpty(url.getUrl())) {
            HttpUtil.api.loadRooms(Collections.emptyMap())
                    .enqueue(new DataCallBack<>(
                            rooms -> {
                                boolean hasLive = !rooms.isEmpty();
                                if (hasLive) {
                                    LiveFragment liveFragment = new LiveFragment();
                                    liveFragment.setOnLiveAllCompletionListener(() -> {
                                        initFragments();
                                        initViewpager(false);
                                        return null;
                                    });
                                    initFragments();
                                    mFragments.add(2, Pair.create("直播", liveFragment));
                                    initViewpager(true);
                                }
                                return null;
                            },
                            throwable -> null
                    ));
        }
    }

    private void initViewpager(boolean hasLive) {
        mDataBind.viewPage.setAdapter(mAdapter = new FragmentStatePagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return mFragments.get(i).second;
            }

            @Override
            public int getCount() {
                return mFragments.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return mFragments.get(position).first;
            }
        });
        mDataBind.viewPage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mCurPage = position;
                if (noLiveFragment()) {
                    loadLive();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mDataBind.tabLayout.setViewPager(mDataBind.viewPage);
        mDataBind.viewPage.setOffscreenPageLimit(mFragments.size());
        if (hasLive) {
            mDataBind.tabLayout.onPageSelected(3);
            mDataBind.viewPage.setCurrentItem(3);
            View root = mDataBind.tabLayout.getChildAt(0);
            if (root instanceof ViewGroup) {
                View liveTabView = ((ViewGroup) root).getChildAt(2);
                if (liveTabView instanceof RelativeLayout) {
                    TextView textView = new TextView(mContext);
                    textView.setText("LIVE");
                    textView.setTextColor(Color.WHITE);
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 9);
                    textView.setGravity(Gravity.CENTER);
                    textView.getPaint().setFakeBoldText(true);
                    textView.setBackgroundResource(R.drawable.live_tag_bg);
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(UiHelper.dp2px(24), UiHelper.dp2px(13));
                    params.addRule(RelativeLayout.ALIGN_PARENT_END);
                    textView.setLayoutParams(params);
                    ((RelativeLayout) liveTabView).addView(textView);
                }
            }
        } else {
            mDataBind.tabLayout.onPageSelected(2);
            mDataBind.viewPage.setCurrentItem(2);
        }
    }

    private boolean noLiveFragment() {
        for (Pair<String, Fragment> pair : mFragments) {
            if (pair.second instanceof LiveFragment) {
                return false;
            }
        }
        return true;
    }

    private Fragment getKsFragment() {
        return AdManager.getShortVideoFragment();
    }

    @Override
    public void onPause() {
        super.onPause();
        AppHelper.mShortVideoTimes = -1;
    }

    @Override
    protected void onLoadData() {
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.my:
                Router.turnTo(mContext, VideoProfileActivity.class)
                        .checkLogin(true)
                        .putExtra(Constants.Extra.Uid, UserManager.getUserId())
                        .start();
                break;

            case R.id.push:
                Router.turnTo(mContext, VideoPublishActivity.class)
                        .checkLogin(true)
                        .start();
                break;

            case R.id.search:
                break;
        }
    }
}
